package cn.cdzdjd.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.json.JSONObject;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import cn.cdzdjd.exception.ErrorCode;
import cn.cdzdjd.exception.RenException;
import cn.cdzdjd.service.XinPianChangService;
import cn.cdzdjd.util.JsoupUtil;
import cn.cdzdjd.util.UrlUtil;
import cn.cdzdjd.vo.VideoInfoVO;

@Service
public class XinPianChangServiceImpl implements XinPianChangService {

	@Resource
	private RestTemplate restTemplate;
	private final String baseUrl = "https://mod-api.xinpianchang.com/mod/api/v2/media/{vid}?appKey={appkey}&extend=userInfo,CuserStatus";

	@Override
	public VideoInfoVO getVideoInfo(String url) {
		Document doc = JsoupUtil.getDocument(url);
		Element body = doc.body();
		Element element = body.selectFirst("script[id=__NEXT_DATA__]");
		String info = element.data();
		JSONObject jsonInfo = new JSONObject(info);
		JSONObject detail = jsonInfo.getJSONObject("props").getJSONObject("pageProps").getJSONObject("detail");
		JSONObject video = detail.getJSONObject("video");
		String vid = video.getString("vid");
		String appKey = video.getString("appKey");
		Map<String, String> map = new HashMap<>();
		map.put("vid", vid);
		map.put("appkey", appKey);
		String jsonStr = restTemplate.getForObject(baseUrl, String.class, map);
		JSONObject json = new JSONObject(jsonStr);
		if (json.getInt("status") == 0) {
			JSONObject data = json.getJSONObject("data");
			String cover = data.getString("cover");
			String title = data.getString("title");
			JSONObject videoInfo = data.getJSONObject("resource").getJSONArray("progressive").getJSONObject(0);
			String videoUrl = videoInfo.getString("backupUrl");
			List<String> videoList = new ArrayList<>();
			videoList.add(UrlUtil.setHttps(videoUrl));
			List<String> posterList = new ArrayList<>();
			posterList.add(UrlUtil.setHttps(cover));
			return new VideoInfoVO(videoList, posterList, title, null);
		} else {
			throw new RenException(ErrorCode.PARSE_ERROR, "解析失败");
		}
	}

}
